<template>
  <div v-loading="loading">
    <el-row :gutter="10">
      <el-col
        :span="12"
        style="text-align: left;"
      >
        <el-date-picker
          v-model="tableDatas.filters.MONTH"
          value-format="YYYY/MM"
          format="YYYY/MM"
          type="month"
        />
        <el-button
          style="display:inline;margin: 0px 0px 0px 10px"
          type="success"
          @click="buttonClick.exportBtnClick"
        >月度调整工时导出</el-button>
        <el-button
          type="success"
          @click="buttonClick.yearBtnClick"
        >{{tableDatas.filters.MONTH.substr(0, 4)}}年度报表导出</el-button>
        <!-- <el-input
          style="display:inline;margin: 0px 12px"
          v-model="tableDatas.filters.searchText"
          clearable
        >
          <template #prepend>搜索</template>
        </el-input> -->
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'修改'"
      top="5vh"
    >
      <el-scrollbar max-height="70vh">
        <el-form :model="dialogDatas.currentData">
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <div v-if="item.isDate">
              <el-date-picker
                v-model="dialogDatas.currentData[item.value]"
                :type="item.dateOption ? item.dateOption.type : 'date'"
                :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
                :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
                :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
                :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
                :disabled="item.disable"
              />
            </div>

            <div
              v-else-if="item.isSelect"
              style="width: 100%"
            >
              <el-select
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
                filterable
              >
                <el-option
                  v-for="item in item.selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <div
              v-else-if="item.isSwitch"
              style="width: 100%"
            >
              <el-switch
                v-model="dialogDatas.currentData[item.value]"
                inline-prompt
                active-text="启用"
                inactive-text="不启用"
                :active-value="item.trueValue"
                :inactive-value="item.falseValue"
                :disabled="item.disable"
              />
            </div>
            <div
              v-else
              style="width: 100%"
            >
              <el-input
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
              />
            </div>
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-table
      class="marginTop10"
      :data="tableDatas.tableDatasAfterPage"
      stripe
      border
      empty-text="无数据"
      max-height="80vh"
    >
      <el-table-column
        v-for="column in tableDatas.tableColumns"
        :type="column.type"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
      >
        <template
          #default="scope"
          v-if="column.prop =='operate'"
        >
          <div>
            <el-button
              type="success"
              @click="tableDatas.editBtnClick(scope.row)"
            >修改</el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定删除该条记录?"
              @confirm="tableDatas.deleteBtnClick(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>

        <template
          #default="scope"
          v-if="column.prop =='ADJUST_TIME'"
        >
          <div>
            <el-input
              v-model="scope.row.ADJUST_TIME"
              @input="tableDatas.changeTime(scope.row,'ADJUST_TIME')"
            >
            </el-input>
          </div>
        </template>

        <template
          #default="scope"
          v-if="column.prop =='HQ_TIME'"
        >
          <div>
            <el-input
              v-model="scope.row.HQ_TIME"
              @input="tableDatas.changeTime(scope.row,'HQ_TIME')"
            >
            </el-input>
          </div>
        </template>

      </el-table-column>
    </el-table>

    <!-- <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination> -->

    <div class="marginTop10">
      <el-button
        type="success"
        @click="buttonClick.submitBtnClick"
      >提交</el-button>
    </div>
  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import { v4 } from 'uuid';
import myAxios from '@/myAxios/myAxios';
import { showWarning } from '@/hooks/useMyMessageBox';
import myAxios193 from '@/myAxios/myAxios193';
import { dayjs } from 'element-plus';
import useMyXlsx from '@/hooks/useMyXlsx';

export default {
  name: 'AdjustView',
  setup () {
    let loading = ref(false);

    let yearBtnClick = async function () {
      let dataContent = {
        year: `${tableDatas.filters.MONTH.substr(0, 4)}`,
      };
      let result = await myAxios193.get('pszx/getGSYearReportUrl', JSON.stringify(dataContent));
      if (result.data.includes('http')) {
        window.open(result.data);
      }
      else {
        showWarning('获取数据失败!' + result.data);
      }
      //   console.log('result :>> ', result);
    };
    let submitBtnClick = function () {
      let submitDatas = tableDatas.oritableData.filter(el => el['CHANGED']);
      let mainParamArr = submitDatas.map(el => {
        let param = `${tableDatas.filters.MONTH}\t${el['P_ID']}`
          + `\t${el['ADJUST_TIME']}\t${el['HQ_TIME']}\t${el['ADJUST_MONEY']}`;
        return param;
      });
      console.log('mainParamArr :>> ', mainParamArr);
      let dataContent = {
        requestNames: ['陈帅廷添加或修改配送中心月度工时/工资',],
        requestParamsArrs: [mainParamArr],
        requestFactorys: ["9900"],
      };

      myAxios193.post('users/postDiffMutipleRequests', JSON.stringify(dataContent)).then(async res => {
        if (res.returnData.message.includes('全部成功')) {
          loading.value = false;

          ElMessage({
            showClose: true,
            type: 'success',
            message: '提交成功!',
          });
          getTableDatas();
          // tableDatas.filters.P_ID = '';

        }
        else {
          loading.value = false;
          showWarning('更新失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('更新失败err!' + err);
      });
    };

    let exportBtnClick = async function () {
      let xlsx = useMyXlsx();
      let rankDatas = await myAxios.get('陈帅廷查询配送中心人员等级');
      rankDatas.forEach(el => {
        // el.ADJUST_TIME = tableDatas.oritableData.find(item => item.P_ID == el.P_ID).ADJUST_TIME;
        let item = tableDatas.oritableData.find(item => item.P_ID == el.P_ID);
        if (item) {
          el.ADJUST_TIME = item.ADJUST_TIME;
        }
        else {
          el.ADJUST_TIME = 0;
        }
      });
      // let exPorps = ['', 'operate', 'P_ID'];
      // let columns = tableDatas.tableColumns.filter(item => !exPorps.includes(item.prop));
      let titles = {
        'NAME': '填报人',
        'RANK_NUM': '岗位技能等级',
        'DGBZ': '定额标准',
        'RANK': '等级:ABCD',
        'DEJZ': '定额基数',
        'P_TYPE': '正式工/外包工/岗位工',
        'ADJUST_TIME': '总定额',
      };
      let header = ['NAME', 'RANK_NUM', 'DGBZ', 'RANK', 'DEJZ', 'P_TYPE', 'ADJUST_TIME'];
      let hideColumns = Object.keys(rankDatas[0]).filter(item => !header.includes(item));
      // for (let index = 0; index < columns.length; index++) {
      //   const element = columns[index];
      //   titles[element.prop] = element.label;
      //   header.push(element.prop);
      // }
      let exportOption = {
        titles,
        header,
        hideColumns,
      };

      xlsx.exportDatas(rankDatas, exportOption, tableDatas.filters.MONTH + '人员调整工时.xlsx');
    };

    let buttonClick = {
      yearBtnClick,
      submitBtnClick,
      exportBtnClick,
    };

    let showFormDialog = function (row) {
      if (row) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = {};
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        {
          "value": "REPORT_TIME",
          "label": "填报时间",
          "isDate": false
        },
        {
          "value": "P_ID",
          "label": "填报人ID",
          "isDate": false
        },
        {
          "value": "WORK_TIME",
          "label": "总工时",
          "isDate": false
        },
        {
          "value": "ADJUST_TIME",
          "label": "调整工时",
          "isDate": false
        },
        {
          "value": "REPORT_ID",
          "label": "REPORT_ID",
          "isDate": false
        },
        {
          "value": "REPORT_DATE",
          "label": "填报日期",
          "isDate": false
        },
        {
          "value": "EMP_DEPARTMENT",
          "label": "部门",
          "isDate": false,
          "disable": false,
          "isSelect": true,
          "selectOptions": [
            {
              "value": "value_1",
              "label": "label_1"
            },
            {
              "value": "value_2",
              "label": "label_2"
            }
          ]
        },
        {
          "value": "DATE_TIME",
          "label": "精确到秒的时间(示例,可删除)",
          "isDate": true,
          "dateOption": {
            "type": "datetime",
            "format": "YYYY/MM/DD HH:mm:ss",
            "dateFormat": "YYYY/MM/DD",
            "timeFormat": "HH:mm:ss",
            "valueFormat": "YYYY/MM/DD HH:mm:ss"
          }
        }
      ],
      confirmBtnClick: function () {
        loading.value = true;
        let row = dialogDatas.currentData;
        let P_ID = row.P_ID ? row.P_ID : v4();

        let params = `${REPORT_TIME}`
          + `\t${dialogDatas.currentData.P_ID}`
          + `\t${dialogDatas.currentData.WORK_TIME}`
          + `\t${dialogDatas.currentData.ADJUST_TIME}`
          + `\t${dialogDatas.currentData.REPORT_ID}`
          + `\t${dialogDatas.currentData.REPORT_DATE}`;
        myAxios.post('添加或更新', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!' + res
            });
            getTableDatas();
          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = function () {
      loading.value = true;

      let params = `${tableDatas.filters.MONTH}`;
      myAxios.get('陈帅廷查询配送中心月度工时/工资', params).then(res => {
        if (res instanceof Array) {
          loading.value = false;
          res.forEach(el => {
            el['WORK_TIME'] = el['WORK_TIME'].toFixed(2);
            el['WORK_MONEY'] = el['WORK_MONEY'].toFixed(2);
            el['SJ_MONEY'] = el['SJ_MONEY'].toFixed(2);
            el['ADJUST_TIME'] = el['ADJUST_TIME'].toFixed(2);
            el['HQ_TIME'] = el['HQ_TIME'].toFixed(2);
            el['ADJUST_MONEY'] = el['ADJUST_MONEY'].toFixed(2);
          });
          tableDatas.oritableData = [...res,];
          //   ElMessage({
          //     showClose: true,
          //     type: 'success',
          //     message: '最新数据获取成功!'
          //   });
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    onMounted(() => {
      getTableDatas();
    });

    let searchKeys = [];
    let tableDatas = reactive({
      //表格筛选展示相关代码
      filters: {
        searchText: '',
        MONTH: dayjs().format('YYYY/MM'),

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;

        if (tableDatas.filters.searchText) {
          let searchText = tableDatas.filters.searchText;
          fData = fData.filter(item => {
            return searchKeys.some(key => {
              return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
            });
          });
        }

        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      tableColumns: [
        {
          "type": "index",
          "prop": "",
          "label": "序号",
          "align": "center",
          "width": 60
        },
        // {
        //   "prop": "REPORT_TIME",
        //   "label": "填报时间",
        //   "align": "center"
        // },
        {
          "prop": "NAME",
          "label": "填报人",
          "align": "center"
        },
        {
          "prop": "WORK_TIME",
          "label": "总工时",
          "align": "center"
        },
        {
          "prop": "ADJUST_TIME",
          "label": "调整工时",
          "align": "center"
        },
        {
          "prop": "HQ_TIME",
          "label": "后勤工资",
          "align": "center"
        },
        {
          "prop": "SJ_MONEY",
          "label": "司机工资",
          "align": "center"
        },
        {
          "prop": "WORK_MONEY",
          "label": "总工资",
          "align": "center"
        },
        {
          "prop": "ADJUST_MONEY",
          "label": "调整工资",
          "align": "center"
        },
        // {
        //   "prop": "operate",
        //   "label": "操作",
        //   "align": "center",
        //   "width": 170
        // }
      ],
      oritableData: [
      ],
      changeTime (row, key) {
        console.log('key :>> ', key);
        if (['ADJUST_TIME', 'HQ_TIME'].includes(key)) {
          let xs = row['DGBZ'] * 0.4 + row['DEJZ'] * 0.6;
          let sum_time = Number(row['ADJUST_TIME']);
          let hq_money = Number(row['HQ_TIME']);;
          let sj_money = Number(row['SJ_MONEY']);
          let ADJUST_MONEY = (hq_money + sj_money + sum_time * xs).toFixed(2);
          row['ADJUST_MONEY'] = ADJUST_MONEY;
          row['CHANGED'] = true;
        }
      },


      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;
        let P_ID = row.P_ID;

        let params = `${P_ID}`;
        myAxios.post('删除', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '删除成功!' + res
            });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },
    });

    watch(() => tableDatas.filters.MONTH, (newVal, oldVal) => {
      if (newVal) {
        getTableDatas();
      }
      else {
        tableDatas.oritableData = [];
      }
    });

    return {
      loading,
      buttonClick,
      dialogDatas,
      tableDatas
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

